//
//  SchemeProductList.m
//  cutter
//
//  Created by mac on 16/3/15.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherCart.h"
#import "UserCenterPick.h"
#import "SchemeProductList.h"
@implementation SchemeProductLeftCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
    [self setNeedsLayout];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    if (self.selected) {
        [self setBackgroundColor:[UIColor whiteColor]];
        [self.nameView setTextColor:[UIColor colorWithHex:0x4794EF]];
        [self.iconView setBlend:self.nameView.textColor];
    }else{
        [self setBackgroundColor:[UIColor colorWithHex:0xF8F8F8]];
        [self.nameView setTextColor:[UIColor blackColor]];
        [self.iconView setBlend:nil];
    }
}
@end

@implementation SchemeProductCellCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:self.node.select animated:animated];
    [self.selectView setSelected:self.node.select];
}
@end

//
@implementation SchemeProductHead
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:self.node.select animated:animated];
    [self.selectView setSelected:self.node.select];
}
@end

//产品清单
@implementation SchemeProductList
+(id)convertData:(NSArray*)data{
    NSMutableArray *array = [NSMutableArray array];
    for (id group in data) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        for (id product in [group objectForKey:@"products"]) {
            id key = @"";
            if ([product objectForKey:@"section"]==nil || [[product objectForKey:@"section"] isEqualToString:@"单品"]) {
            }else{
                key = [product objectForKey:@"section"];
            }
            if (key) {
                id items = [temp objectForKey:key];
                if (items == nil) {
                    items = [NSMutableArray array];
                    [temp setValue:items forKey:key];
                }
                [items addObject:product];
            }
        }
        //
        NSMutableArray *arr1 = [NSMutableArray array];
        for (id key in temp.allKeys) {
            NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
            [dic2 setValue:[temp objectForKey:key] forKey:@"items"];
            [dic2 setValue:key forKey:@"name"];
            [arr1 addObject:dic2];
        }
        //
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        [dic1 setValue:[group objectForKey:@"name"] forKey:@"name"];
        [dic1 setValue:arr1 forKey:@"items"];
        //
        [array addObject:dic1];
    }
    return array;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.presentationController) {
        UIView *parent = [[self.navigationController view] superview];
        if (parent) {
            [parent.layer setCornerRadius:6];
        }else{
            parent = [self.view superview];
            if (parent) {
                [parent.layer setCornerRadius:6];
            }
        }
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectCell:) name:@"didSelectCell" object:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)didSelectCell:(NSNotification *)info{
    NSInteger index = 0;
    NSIndexPath *indexpath = info.object;
    for (UITreeNode *node in self.mainView.visibleNodes) {
        if (node.level == 0) {
            if (index == indexpath.item) {
                NSInteger i = [self.mainView indexAtNode:node];
                [self.mainView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                return;
            }
            index++;
        }
    }
}
-(void)viewDidLoad{
    [super viewDidLoad];
    [self reloadData];
}
-(void)reloadData{
    if (self.data && [self.data isKindOfClass:NSArray.class]) {
        __weak SchemeProductList *this = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [this makeDetail];
            NSDictionary *source = [NSDictionary dictionaryWithObject:[SchemeProductList convertData:this.data] forKey:@"items"];
            UITreeNode *root = [this makeNodesWithData:source level:-1];
            dispatch_async(dispatch_get_main_queue(), ^{
                [this.mainView setRootNode:root];
                [this updata];
                self.allView.selected = NO;
                [self.allView sendActionsForControlEvents:UIControlEventTouchUpInside];

            });
        });
    }
}
-(void)makeDetail{
    NSMutableArray *ids = [NSMutableArray array];
    for (id item in self.data) {
        id products = [item objectForKey:@"products"];
        for (id product in products) {
            id key = [product objectForKey:@"id"];
            if (key) {
                [ids addObject:key];
            }
        }
    }
    //
    if ([ids count] > 0) {
        NSMutableDictionary *arg = [NSMutableDictionary dictionary];
        [arg setValue:[ids componentsJoinedByString:@","] forKey:@"productid"];
        //
        NSArray *details = [AppData productDetail:[ids componentsJoinedByString:@","]];
        if (details) {
            NSMutableDictionary *detail = [NSMutableDictionary dictionary];
            for (id tmp in details) {
                id key = [tmp objectForKey:@"id"];
                [detail setValue:tmp forKey:key];
            }
            for (id item in self.data) {
                id products = [item objectForKey:@"products"];
                for (id product in products) {
                    id key = [product objectForKey:@"id"];
                    [product setValue:[detail objectForKey:key] forKey:@"product_detail"];
                }
            }
        }
    }
}
-(UITreeNode*)makeNodesWithData:(id)data level:(NSInteger)level{
    static NSInteger identify = 0;
    if ([data isKindOfClass:NSDictionary.class]) {
        UITreeNode *nodes=[[UITreeNode alloc] init];
        nodes.idetify = identify++;
        nodes.level = level;
        nodes.expand = YES;
        nodes.select = NO;
        nodes.value = data;
        //子级列出
        id child = [data objectForKey:@"items"];
        if (child) {
            for (id item in child) {
                [nodes addNode:[self makeNodesWithData:item level:level+1]];
            }
        }
        return nodes;
    }
    return nil;
}
//
-(void)treeView:(UITreeView *)treeView expandRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    [self selectNode:node];
    [self updata];
}
-(void)treeView:(UITreeView *)treeView collapseRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    [self deselectNode:node];
    [self updata];
}
-(UITableViewCell *)treeView:(UITreeView *)treeView cellForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level == 0) {
        SchemeProductHead *cell = [treeView dequeueReusableCellWithIdentifier:@"headIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        [cell setNode:node];
        return cell;
    }
    if (node.level == 1) {
        SchemeProductHead *cell = [treeView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        [cell setNode:node];
        return cell;
    }
    
    SchemeProductCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    id detail = [node.value objectForKey:@"product_detail"];
    if (detail) {
        [cell.countView setText:[AppData objToString:[node.value objectForKey:@"productcount"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
        [cell.nameView setText:[AppData objToString:[detail objectForKey:@"productname"] lable:nil]];
        [cell.sizeView setText:[AppData objToString:[detail objectForKey:@"productsn"] lable:nil]];
        [AppData loadImage:[detail objectForKey:@"thumb400_jpg"] view:cell.iconView];
    }
    [cell setNode:node];
    return cell;
}
-(CGFloat)treeView:(UITreeView *)treeView heightForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level < 2) {
        if ([[node.value objectForKey:@"name"] isEqualToString:@""]) {
            return 0;
        }
        return 40;
    }
    return 119;
}
-(void)selectNode:(UITreeNode*)node{
    if (node) {
        [node setSelect:YES];
        for (UITreeNode *item in node.nodes) {
            [self selectNode:item];
        }
    }
}
-(void)deselectNode:(UITreeNode*)node{
    if (node) {
        [node setSelect:NO];
        for (UITreeNode *item in node.nodes) {
            [self deselectNode:item];
        }
    }
}
-(id)deleteNode:(UITreeNode*)node{
    NSMutableArray *array = [NSMutableArray array];
    if (node) {
        if (node.select && node.level == 2) {
            [array addObject:node.value];
            [node.parent removeNode:node];
        }else{
            for (UITreeNode *item in node.nodes) {
                [array addObjectsFromArray:[self deleteNode:item]];
            }
        }
    }
    return array;
}
-(IBAction)ctrlTouch:(UIButton*)sender{
    if (self.allView == sender) {
        [sender setSelected:!sender.selected];
        //
        if (sender.selected) {
            [self selectNode:self.mainView.rootNode];
        }else{
            [self deselectNode:self.mainView.rootNode];
        }
    }
    [self.mainView displayNodes];
    [self updata];
}
//
-(void)updata{
    CGFloat price = 0;
    NSInteger count = 0;
    NSArray *selected = [self.mainView visibleNodes];
    for (UITreeNode *node in selected) {
        if (node.select && node.level == 2) {
            id temp = [node.value objectForKey:@"product_detail"];
            if (temp && [temp isKindOfClass:NSDictionary.class]) {
                NSInteger c = [[node.value objectForKey:@"productcount"] integerValue];
                CGFloat p = [[temp objectForKey:@"price"] floatValue];
                price += c * p;
                count += c;
            }
        }
    }
    [self.countView setText:[NSString stringWithFormat:@"%ld", (long)count]];
    [self.totalPrice setText:[NSString stringWithFormat:@"￥%0.2f", price]];
    [self.salePrice setText:[NSString stringWithFormat:@"￥%0.2f", price]];
    [self.cartView setEnabled:count>0];
}
//
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"cartSegue"]) {
            [self addCartTouch:sender];
        }
        return NO;
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    __weak SchemeProductList *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterPick.class]) {
            UserCenterPick *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [TMGlobal setValue:result forKey:@"client"];
                [ctrl dismissViewControllerAnimated:YES completion:^{
                    if ([segue.identifier isEqualToString:@"cartSegue"]) {
                        [this addCartTouch:sender];
                    }
                }];
            }];
        }
    }
}
-(void)addCartTouch:(UIButton*)sender{
    id client = [TMGlobal valueForKey:@"client"];
    if (client) {
        NSMutableArray *carts = [NSMutableArray array];
        NSArray *selected = [self.mainView visibleNodes];
        for (UITreeNode *node in selected) {
            if (node.select && node.level == 2) {
                id temp = [node.value objectForKey:@"product_detail"];
                if (temp && [temp isKindOfClass:NSDictionary.class]) {
                    id item = [NSMutableDictionary dictionaryWithDictionary:temp];
                    [item setValue:[node.value objectForKey:@"productcount"] forKey:@"count"];
                    [item setValue:[node.value objectForKey:@"matchid"] forKey:@"matchid"];
                    [item setValue:[node.value objectForKey:@"suitid"] forKey:@"suitid"];
                    [carts addObject:item];
                }
            }
        }
        if ([AppData userAddCart:carts client:client]) {
            [TMAlert showAtView:self.view image:@"img_Prompt_ShoppingCar_OK.png"];
        }
    }
}
@end
